package jsp;

import entity.Emp;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月02日16:12
 */
@WebServlet("*.ems")
public class EmsServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path=request.getServletPath();
        // System.out.println(path);
        switch (path){
            case "/add.ems":
                addEmp(request,response);
                break;
            case "/findAll.ems":
                findAll(request,response);
                break;
            case "/findById.ems":
                findById(request,response);
                break;
            case "/modify.ems":
                modifyEmp(request,response);
                break;
            case "/deleteById.ems":
                deleteEmp(request,response);
                break;

        }
    }

    public void addEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("name");


        System.out.println(name);
        String salary=request.getParameter("salary");
        String gender=request.getParameter("gender");
        String edu=request.getParameter("edu");
        String[] hobbies=request.getParameterValues("hobbies");

        Connection conn=null;
        PreparedStatement ps=null;
        String url="jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" insert into t_emp ")
                    .append(" (name,salary,gender,edu,hobbies) ")
                    .append(" values  ")
                    .append(" (?,?,?,?,?) ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));

            //执行DML操作
            ps.executeUpdate();

            // 在request中，可以绑定数据
            // request.setAttribute(key,value)
            // request.getAttribute(key)根据key获取值
            // request.setAttribute("msg","哈哈哈哈");
            // System.out.println(request.getAttribute("msg"));
            // response.sendRedirect(request.getContextPath()+"/ems/empList.jsp");
            response.sendRedirect(request.getContextPath()+"/findAll.ems");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            request.setAttribute("msg","类加载失败");
            request.getRequestDispatcher("/ems/addEmp.jsp").forward(request,response);

        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("msg","数据库访问异常");
            request.getRequestDispatcher("/ems/addEmp.jsp").forward(request,response);
        } finally {
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    public void findAll(HttpServletRequest request, HttpServletResponse response){
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List<Emp> emps=new ArrayList<>();
        String url="jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .toString();
            ps=conn.prepareStatement(sql);
            rs=ps.executeQuery();
            while(rs.next()){
                Emp emp=new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setGender(rs.getString("gender"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
                emps.add(emp);
            }

            request.setAttribute("emps",emps);
            // request.getRequestDispatcher("/ems/empList.jsp").forward(request,response);
            request.getRequestDispatcher("/ems2/empList.jsp").forward(request,response);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void findById(HttpServletRequest request, HttpServletResponse response){
        String id=request.getParameter("id");
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        String url="jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .append(" where id=? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            rs=ps.executeQuery();
            if(rs.next()){
                Emp emp=new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setGender(rs.getString("gender"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
                request.setAttribute("emp",emp);
                // request.getRequestDispatcher("/ems/modifyEmp.jsp").forward(request,response);
                request.getRequestDispatcher("/ems2/modifyEmp.jsp").forward(request,response);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
    }
    public void modifyEmp(HttpServletRequest request, HttpServletResponse response){
        String id=request.getParameter("id");
        String name=request.getParameter("name");
        System.out.println(name);
        String salary=request.getParameter("salary");
        String gender=request.getParameter("gender");
        String edu=request.getParameter("edu");
        String[] hobbies=request.getParameterValues("hobbies");
        Connection conn=null;
        PreparedStatement ps=null;
        String url="jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set name=?,salary=?,gender=?,edu=?,hobbies=? ")
                    .append(" where id=? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            ps.setInt(6,Integer.parseInt(id));
            //执行DML操作
            ps.executeUpdate();

            response.sendRedirect(request.getContextPath()+"/findAll.ems");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭释放资源
        }
    }
    public void deleteEmp(HttpServletRequest request, HttpServletResponse response){
        String id=request.getParameter("id");
        Connection conn=null;
        PreparedStatement ps=null;
        String url="jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" delete from t_emp  ")
                    .append(" where id=? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            ps.executeUpdate();
            response.sendRedirect(request.getContextPath()+"/findAll.ems");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭释放资源
        }
    }

}
